package api;

import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;
import util.SessionUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @description: 删除菜品
 * @author: chengbaiyi
 * @create: 2022-06-27 11:23
 */
@WebServlet("/deldish")
public class DelDishServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state = -1;
        String msg = "未知错误";
        UserInfo userInfo = SessionUtil.getSessionUserInfo(req);
        if (userInfo != null) {
            int did = Integer.parseInt(req.getParameter("did"));
            if (did > 0) {
                Connection connection = DBUtil.getConnection();
                // 删除之前，要先确认订单详情表没有使用此菜品
                // 如果未完成订单中存在该菜品，则删除失败
                String sql = "select * from `order` where state=0 and oid=(select oid from `orderdetail` where did=?)";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1, did);
                ResultSet  resultSet = statement.executeQuery();
                if (resultSet.next()) {
                    // 存在订单，无法删除
                    msg = "未完成订单中存在该菜品，删除失败！";
                } else {
                    sql = "delete from dish where did=?";
                    PreparedStatement statement2 = connection.prepareStatement(sql);
                    statement2.setInt(1, did);
                    int result = statement2.executeUpdate();
                    DBUtil.close(null, statement2, null);
                    state = result >= 1 ? 200 : -1;
                    msg = "删除成功！";
                }
                DBUtil.close(null, statement, connection);
            }
        } else {
            msg = "未知错误";
        }
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        resp.getWriter().println(
                JSONUtil.toJsonStr(new ResultData(state, "", msg))
        );
    }
}
